import axios from 'axios'
import PubSub from 'pubsub-js'
import React, { Component } from 'react'


export default class Search extends Component {

  // 搜索按钮
  search = ()=>{
    // 获取用户输入
    const {input1}= this
    const searchName = input1.value
    // 告诉App，loading
    PubSub.publish('MY TOPIC', {users:[], isFirst:false, isLoading:true, isErr:''});
    // this.props.search({users:[], isFirst:false, isLoading:true, isErr:''})
    // 发起网络请求
    axios.get(`http://localhost:3000/api1/search/users?q=${searchName}`)
    .then(res=>{
      const newUsers = res.data.items
      // console.log(newUsers)
      PubSub.publish('MY TOPIC', {users:newUsers, isFirst:false, isLoading:false, isErr:''});
      // this.props.search({users:newUsers, isFirst:false, isLoading:false, isErr:''})
    })
    .catch(err=>{
      // console.log(err)
      PubSub.publish('MY TOPIC', {users:[], isFirst:false, isLoading:false, isErr:JSON.stringify(err)});
      // this.props.search({users:[], isFirst:false, isLoading:false, isErr:JSON.stringify(err)})
    })
  }
  // 渲染
  render() {
    return (
      <section className="jumbotron">
        <h3 className="jumbotron-heading">Search Github Users</h3>
        <div>
          <input type="text" ref={currentNode=>this.input1=currentNode} placeholder="enter the name you search"/>&nbsp;
          <button onClick={this.search}>Search</button>
        </div>
      </section>
    )
  }
}
